const Controller = require('/pages/controllers/Controller.js').controller;
const request = require('./utils/kzj.request.js');

App({
  onLaunch: function(option) {

    //获取token
    let token = wx.getStorageSync('token') || '';
    //优先判断token
    if (token) {
      //延时判断微信服务器Session状态
      setTimeout(() => {
        wx.checkSession({
          success: () => {
            //session_key 未过期，并且在本生命周期一直有效
          },
          fail: () => {
            // session_key 已经失效，需要重新执行登录流程
            this.GetLogin(false);
          }
        });
      }, 1500);
    } else {
      //无token，直接登录
      this.GetLogin();
    }

    //异步更新 + 强制更新

    // wx.getUpdateManager 在 1.9.90 才可用，请注意兼容
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
      if(res.hasUpdate){
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否马上重启小程序？',
          success: function(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        });
      }
    });

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否马上重启小程序？',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      });
    })

    updateManager.onUpdateFailed(function() {
      wx.showModal({
         title: '已有新版本',
         content: '新版本已经上线了，请删除当前小程序，重新搜索打开',
      })
    });

    // 获取手机系统信息
    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.globalData.navHeight = res.statusBarHeight + 46;
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  onShow() {
    var that = this;
    const agentLogin = wx.getStorageSync('agentLogin');
    that.globalData.agentLogin = agentLogin;
  },
  judgeAgent(cb) {
    var that = this;
    const agentLogin = wx.getStorageSync('agentLogin');
    console.log('app.agentLogin==', agentLogin);
    
    if (!agentLogin || Object.keys(agentLogin).length === 0) {
      // cb && typeof(cb) && cb(0);
      that.ToLogin('需绑定手机号');
    } else {
      cb && typeof(cb) && cb(agentLogin.type);
    }
  },
  ToLogin(msg) {
    var that=this;
    if(that.globalData.islogin){
      that.globalData.islogin=false
      wx.showModal({
        title: '提示',
        content: msg || '是否授权登录?',
        success(res) {
          that.globalData.islogin=true
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/Login/login"
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  //登录请求
  GetLogin(flag) {
    if (flag == undefined || flag) {
      wx.showLoading({
        title: '登录中...',
        mask: true
      });
    }
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        Controller.appletLogin({
          code: res.code
        }).then(result => {
          console.log('appletLogin--result==', result);
          if(result.data.sessionKey){
            this.globalData.sessionKey=result.data.sessionKey
          }
          if(result.data.sessionId){
            wx.setStorageSync('token', result.data.sessionId)
          }
          this.globalData.openId=result.data.openId
          if (this.tokenReadyCallback) {
            this.tokenReadyCallback(result);
          }
          
          if (flag == undefined || flag) {
            wx.hideLoading();
          }
        });
        
      }
    });
  },


  //公共变量
  globalData: {
    islogin:true,
    IMG_URL:'http://111.230.226.223/beauty-industry',
    mobile:'',
    shopId:'',
    myshopinfo:'',
    sessionKey:'',
    openId:'',
    tabbar:[
      {
        "text": "首页",
        "iconPath": "/assets/images/tab/home_icon_21@3x.png",
        "selectedIconPath": "/assets/images/tab/home_icon_20@3x.png"
      },
      {
        "text": "数据统计",
        "iconPath": "/assets/images/tab/statistics_icon_02@3x.png",
        "selectedIconPath": "/assets/images/tab/statistics_icon_01@3x.png"
      },
      {
        "text": "我的",
        "iconPath": "/assets/images/tab/my_icon_02@3x.png",
        "selectedIconPath": "/assets/images/tab/my_icon_01@3x.png"
      }
    ],
    tabPage: ['/pages/Index/index', '/pages/Census/index', '/pages/My/index'],
    contentList:[],
    agentIndexData: {},
    agentLogin: {},
    coupon:null,
  },
  //拨打电话
  calling: function(e) {
    console.log(e)
    wx.makePhoneCall({
      phoneNumber: e || this.globalData.mobile,
      success: function() {
        console.log("拨打电话成功！")
      },
      fail: function() {
        console.log("拨打电话失败！")
      }
    })
  },
  uploadFile(count, cb) {
    console.log('uploadFile--count==', count);
    var that = this;
    let token = wx.getStorageSync('token') || '';
    wx.chooseImage({
      count: count || 1,
      success (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: `${request.url}/api/img/uploadFile`,
          header: {
            'content-type': 'multipart/form-data'
          },
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            sessionId: token
          },
          success (res){
            console.log('app--uploadFile--res==', res);
            const result = JSON.parse(res.data);
            cb && typeof(cb) === 'function' && cb(result.data)
          }
        })
      }
    })
  },
  openPage({ url, type = 'navigateTo' }, cb) {
    var that = this;
    if (!url) {
      return;
    }
    try {
      if (type === 'navigateTo') {
        wx.navigateTo({ url });
      } else if (type === 'reLaunch') {
        wx.reLaunch({ url });
      } else if (type === 'redirectTo') {
        wx.redirectTo({ url });
      }
      cb && typeof (cb) === 'function' && cb(true);
    } catch(e) {
      console.log('e==', e);
      const { errMsg } = e;
      if (e.includes('is not found')) {
        wx.showToast({
          title: e.errMsg,
        })
        cb && typeof (cb) === 'function' && cb({ errMsg, open: false });
      } else {
        cb && typeof (cb) === 'function' && cb({ errMsg, open: true });
      }
    }
  },
  tabChange(e) {
    var that = this;
    console.log('tab change', e)
    var index = e.detail.index;
    var tabPage = wx.getStorageSync('tabPage');
    if (!tabPage) {
      that.openPage({ url: '/pages/Login/login' });
    }
    var url = tabPage[index];
    that.openPage({url, type: 'reLaunch'});
  }
})